from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import numpy as np
from Ui_untitled import Ui_Form

import matplotlib
matplotlib.use("Qt5Agg")  # 声明使用QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

import time
import os

plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一（替换sans-serif字体）
plt.rcParams['axes.unicode_minus'] = False  # 步骤二（解决坐标轴负数的负号显示问题）

import ser
import serial #导入模块
import serial.tools.list_ports

import imu_data

#创建一个matplotlib图形绘制类
class MyFigure(FigureCanvas):
    def __init__(self,width=5, height=4, dpi=100):
        #第一步：创建一个创建Figure
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        #第二步：在父类中激活Figure窗口
        super(MyFigure,self).__init__(self.fig) #此句必不可少，否则不能显示图形
        #第三步：创建一个子图，用于绘制图形用，111表示子图编号，如matlab的subplot(1,1,1)
        # self.axes1 = self.fig.add_subplot(111)
        # self.axes2 = self.fig.add_subplot(412)
        # self.axes3 = self.fig.add_subplot(413)
        # self.axes4 = self.fig.add_subplot(414)
    #第四步：就是画图，【可以在此类中画，也可以在其它类中画】
    def plotsin(self):
        # self.axes0 = self.fig.add_subplot(111)
        t = np.arange(0.0, 3.0, 0.01)
        s = np.sin(2 * np.pi * t)
        self.axes4.plot(t, s)





class MainDialogImgBW(QDialog,Ui_Form):
    def __init__(self):
        super(MainDialogImgBW,self).__init__()
        self.setupUi(self)
        self.time = []
        self.x = []
        self.y = []
        self.z = []
        self.data= []
        self.draw_points = [{'channal':1,'data':[]},
        {'channal':2,'data':[]},
        {'channal':3,'data':[]},
        {'channal':4,'data':[]}]
        self.idx=0
        self.com_list =[]
        self.open_serial = False
        self.recoder_flag = False
        self.create_dir('.\数据存储')

        self.com_list = ser.Print_Used_Com()
        self.comboBox.addItems(self.com_list)
     
        self.gridlayout = QGridLayout(self.groupBox)  # 继承容器groupBox

        dynamic_canvas = FigureCanvas(Figure(figsize=(5, 3)))
        self.gridlayout.addWidget(dynamic_canvas)
        self._dynamic_1 = dynamic_canvas.figure.add_subplot(411)
        self._dynamic_2 = dynamic_canvas.figure.add_subplot(412)
        self._dynamic_3 = dynamic_canvas.figure.add_subplot(413)
        self._dynamic_4 = dynamic_canvas.figure.add_subplot(414)
        
        t = np.linspace(0, 10, 101)    
        # self.F.plotsin()
        # self.plotcos()
        #第六步：在GUI的groupBox中创建一个布局，用于添加MyFigure类的实例（即图形）后其他部件。

        # self.gridlayout.addWidget(self.F,0,1)

        # self._line = self.F.fig.plot(self.data)
         # Set up a Line2D.
        self._line11, = self._dynamic_1.plot(t, np.sin(t + time.time()),color='blue',label="x")
        self._line12, = self._dynamic_1.plot(t, np.sin(t + time.time())-1,color='red',label="y")
        self._line13, = self._dynamic_1.plot(t, np.sin(t + time.time())-1,color='green',label="z")

        self._dynamic_1.set_ylim(-2,2)

        self._line21, = self._dynamic_2.plot(t, np.sin(t + time.time()),color='blue',label="x")
        self._line22, = self._dynamic_2.plot(t, np.sin(t + time.time())-1,color='red',label="y")
        self._line23, = self._dynamic_2.plot(t, np.sin(t + time.time())-1,color='green',label="z")
        self._dynamic_2.set_ylim(-2,2)
        self.lasttime=time.time()
        #实例化一个定时器
        self.timer = QTimer(self)
        self.timer_2 = QTimer(self)
        #定时器调用读取串口接收数据
        self.timer.timeout.connect(self._update_canvas)
        self.timer.start(20)
        self.timer_2.timeout.connect(self.serial_detect)
        self.timer_2.start(1000)

        #补充：另创建一个实例绘图并显示
        # self.plotother()
        
        self.pushButton.clicked.connect(self.click_button)
        self.pushButton_2.clicked.connect(self.click_recoder_button)
    def _update_canvas(self):
        if self.open_serial is True:
            data_dic = []
            try:
                data_dic = self.read_data()
            except Exception as e:
                print("---串口异常---：",e)
                self.pushButton.setText("打开串口")
                self.ser.close()#关闭串口
                self.open_serial = False
            time_now = time.time()-self.lasttime
            # new_data_temp = np.sin(time_now)
            
            self._loop_append_process(self.time,time_now)
            for i in data_dic:
                if i['data'] != []:
                    self._loop_append_process(self.draw_points[1]['data'],i['data'])

                    # if len(self.time) < 100:
                    #     self.x.append(i['data'][0])
                    #     self.y.append(i['data'][1])
                    #     self.z.append(i['data'][2])
                    #     self.draw_points[i]
                    #     self.time.append(time_now)
                    # else:
                    #     self.x[:-1] = self.x[1:]
                    #     self.x[-1] = i['data'][0] 

                    #     self.y[:-1] = self.y[1:]
                    #     self.y[-1] = i['data'][1] 

                    #     self.z[:-1] = self.z[1:]
                    #     self.z[-1] = i['data'][2] 

                    #     self.time[:-1] = self.time[1:]
                    #     self.time[-1] = time_now


                    # if time_now < 10:
                    #     self._dynamic_1.set_xlim(0,time_now)
                    #     self._dynamic_2.set_xlim(0,time_now)
                    #     self._dynamic_3.set_xlim(0,time_now)
                    #     self._dynamic_4.set_xlim(0,time_now)
                    # else:
                    #     # t = np.linspace(time_now-10, time_now,100 )
                    #     self._dynamic_1.set_xlim(time_now-10, time_now)
                    #     self._dynamic_2.set_xlim(time_now-10, time_now)
                    #     self._dynamic_3.set_xlim(time_now-10, time_now)
                    #     self._dynamic_4.set_xlim(time_now-10, time_now)
                        
                
                    # if i['id'] == 1 :
                    #     print(i)
                    #     print(self.z)
                    #     print(self.draw_points[i['id']-1]['data'][0])
                    #     self._line11.set_data(self.time,self.draw_points[i['id']-1]['data'][0])
                    #     self._line11.figure.canvas.draw()   
                        # self._line12.set_data(self.time,self.draw_points[i['id']]['data'][1])
                        # self._line13.set_data(self.time,self.draw_points[i['id']]['data'][2])

                        
                        
                    # if i['id'] == 2 :
                    #     self._line21.set_data(self.time,self.x)
                    #     self._line22.set_data(self.time,self.y)
                    #     self._line23.set_data(self.time,self.z)
                            
            
                # self._line21.figure.canvas.draw() 
                    # self._line2.set_data(t, np.sin(t+time_now)-2)
                    # self._line2.figure.canvas.draw()


                    # self._line3.set_data(t, np.sin(t+time_now)-2)
                    # self._line3.set_data(t, np.sin(t+time_now)-1)
                
                # if self.recoder_flag is True:
                #     self.fp.writelines(str(time_now)+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+'\n')

    def serial_detect(self):
        com_list_temp = ser.Print_Used_Com()
        if (com_list_temp == self.com_list) is False:         
            self.comboBox.clear()
            self.comboBox.addItems(com_list_temp)
        self.com_list = com_list_temp
    def _loop_append_process(self,datas,new_data):
        if len(datas) < 100:
            datas.append(new_data)
        else:
            datas[:-1] = datas[1:]
            datas[-1] = new_data
        return datas

    def read_data(self):
        data_dic = []
        data_dic.append({'id':1,'data':[]})
        data_dic.append({'id':2,'data':[]})
        data_dic.append({'id':3,'data':[]})
        data_dic.append({'id':4,'data':[]})
        data =[]
        id = b'0x15'
        if self.open_serial is True:
            while(self.ser.inWaiting() > 33):
                t_data = self.ser.read(34)

                data = imu_data.DueData(t_data[:-1])
                id = t_data[-1]
                
                if id < 5:
                    data_dic[id-1]['data'] = data
                
        print(data_dic)
        return data_dic

    def click_button(self,bool):
        if self.open_serial is True:
            self.pushButton.setText("打开串口")
            self.ser.close()#关闭串口
            self.open_serial = False
        else:
            self.open_serial = True
            self.pushButton.setText("关闭串口")
            try:
                #端口，GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
                portx= str(main.comboBox.currentText()[:4])
                #波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
                bps=115200
                #超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
                timex=5
                # 打开串口，并得到串口对象
                self.ser=serial.Serial(portx,bps,timeout=timex)
                print(portx)
            except Exception as e:
                print("---异常---：",e)
    def click_recoder_button(self,bool):
        if self.recoder_flag is True:
            self.pushButton_2.setText("开始记录")
            self.recoder_flag = False
            self.label.setText("停止")
            self.fp.close()

        else:
            self.recoder_flag = True
            self.pushButton_2.setText("停止记录")
            self.label.setText("正在记录")
            file_name = time.strftime("%Y-%m-%d-%H%M%S", time.localtime())
            print(file_name)
            self.fp = open('.\数据存储' + '\\' + file_name+'.txt', "w")
            try:
                print('hello')
                
            except Exception as e:
                print("---异常---：",e)
    def create_dir(self, path):
        isExists = os.path.exists(path)
        if not isExists:
            os.makedirs(path)
            print('create folder :' + path)
        else:
            # print('the folder already exists' + '(%s)' % (path))
            pass
        
        




def click_button(bool):
    global ser
    global open_serial
    if open_serial is True:
        main.pushButton.setText("打开串口")
        ser.close()#关闭串口
        open_serial = False
    else:
        open_serial = True
        main.pushButton.setText("关闭串口")
        try:
            #端口，GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
            portx= str(main.comboBox.currentText()[:4])
            #波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
            bps=115200
            #超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
            timex=5
            # 打开串口，并得到串口对象
            ser=serial.Serial(portx,bps,timeout=timex)
            print(portx)
        except Exception as e:
            print("---异常---：",e)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MainDialogImgBW()


    
    main.show()
    

    sys.exit(app.exec_())